/* 
// axton.data : provides data manipulation and ajax features
// Written by: Noah Peters
//
Copyright (c) 2008, Noah Peters
All rights reserved.
Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions 
are met:
	•	Redistributions of source code must retain the above 
	copyright notice, this list of conditions and the following 
	disclaimer.
	•	Redistributions in binary form must reproduce the above 
	copyright notice, this list of conditions and the following 
	disclaimer in the documentation and/or other materials provided 
	with the distribution.
	•	Neither the name of the <ORGANIZATION> nor the names of 
	its contributors may be used to endorse or promote products 
	derived from this software without specific prior written 
	permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
//
*/

/*global axton, ActiveXObject */
/*jslint browser: true, evil: true */
axton.data.ajax.Queue = function (cache) {
    this.queue = [];
    this.pointer = 0;
    this.req = null;
    this.running = false;
    this.enabled = true;
    this.time = null;
    this.nextID = 0;
    this.cache = cache;
       
    this.currentRequest = new axton.data.ajax.Request();
        
    this.isRunning = function () {
        if (this.pointer + 1 < this.queue.length) {
            return this.running;
        } else {
            return false;
        }
    };
    
    this.enable = function () {
        if (!this.enabled) {
            this.enabled = true;
            this.next();    
        }
    };
    
    this.disable = function () {
        if (this.enabled) {
            if (this.req) {
                this.req.abort();
            }
            this.enabled = false;
            this.pointer--;
        }
    };
    
    this.clearAll = function () {
        this.disable();
        while (this.queue.length > 0) {
            this.queue.pop();
        }
        this.enable();
    };
    
    this.remove = function (id) {
        if (this.pointer === id) {
            this.req.abort();
            this.next();
        }
        delete this.queue[id];
        this.queue.length--;
    };
    
    this.loadXMLDoc = function (request) {
        var d;
        if (this.cache) {
            if (this.cache.check(request)===true) {
                return 0;
            }
        }
        d = new Date();
        this.time = d.getTime();
        this.running = true;
        this.currentRequest = request;
        this.req = false;
        
        // branch for native XMLHttpRequest object
        var winax = false;
        if (window.XMLHttpRequest) {
            try {
                this.req = new XMLHttpRequest();
            } catch (e1) {
                this.req = false;
            }
        // branch for IE/Windows ActiveX version
        } else if (window.ActiveXObject) {
            winax = true;
            try {
                this.req = new ActiveXObject("Msxml2.XMLHTTP.6.0");
            } catch (e2) {
                try {
                    try {
                        this.req = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e3) {
                        this.req = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                } catch (e4) {
                    this.req = false;
                }
            }
        }
        if (this.req) {
            var err;
            var rsc = this.readystatechange;
            rsc.req = this; //for firefox style XMLHttpRequests
            try {
                axton.data.ajax.ie6req = this; //for legacy XMLHttpRequests
                this.req.onreadystatechange = rsc;
                this.req.req = this; //for IE7 style XMLHttpRequests
                if (!this.req.onreadystatechange.req && !this.req.req) {
                    err = new axton.error.Exception(
                        "This browser does not support all of the features of axton.data.ajax");
                    err.raise();
                }
            } catch (ee) {
                err = new axton.error.Exception(ee.toString());
                err.raise();
            }
            var headerNames = this.currentRequest.getHeaderNames();
            var headerValues = this.currentRequest.getHeaderValues();
            this.req.open(
                this.currentRequest.method, 
                this.currentRequest.url, true);
            for (var iii = 0; iii < headerNames.length; iii++) {
                this.req.setRequestHeader(
                    headerNames[iii], 
                    headerValues[iii]);
            }
            this.req.send(this.currentRequest.data);
        }
    };
    
    this.readystatechange = function () {
        // only if req shows "loaded"
        var req = this.req ? this.req : null;
        var d;
        var data;
        var contentType;
        if (req === null) {
            req = axton.data.ajax.ie6req;
        }
        if (req.req.readyState === 4) {
            // only if "OK"
            d = new Date();
            this.time = d.getTime() - req.time;
            if (req.req.status === 200) {
                try {
                    contentType = req.req.getResponseHeader("Content-Type");
                    data = null;
                    switch (contentType) {
                        case "application/json" : 
                            data = req.currentRequest.JSONEvilCheck ? JSON.parse(req.req.responseText, req.currentRequest.JSONReviver) : eval("("+req.req.responseText+")");
                            break;
                        case "application/xml" :
                        case "text/xml" :
                            //if (!req.req.responseXML && !req.req.responseXML.firstChild) {
                            //    data = new ActiveXObject("Msxml2.DOMDocument");
                            //    data.loadXML(req.req.responseText);
                            //} else {
                                data = req.req.responseXML;
                            //}
                            break;
                        default : //"text/plain", "text/html"
                            data = req.req.responseText;
                    }
                    if (this.cache) {
                        this.cache.add(req, data);
                    }
                    if (req.currentRequest.callback && 
                            req.currentRequest.callback instanceof axton.eventManager.EventHandler) {
                        req.currentRequest.callback.invoke(
                                req.currentRequest.id, 
                                data,
                                req.req.responseText, 
                                this.time, 
                                req.currentRequest,
                                req.req);
                    } else if (req.currentRequest.callback) {
                        req.currentRequest.callback(
                                req.currentRequest.id, 
                                data,
                                req.req.responseText, 
                                this.time, 
                                req.currentRequest,
                                req.req);
                    }
                } catch (ex) {
                    //alert(ex.message);
                }
                req.next();
            } else {
                data = req.req.responseXML;
                if (req.currentRequest.callerror && 
                        req.currentRequest.callback instanceof axton.eventManager.EventHandler) {
                    req.currentRequest.callerror.invoke(
                            req.currentRequest.id, 
                            data, 
                            req.req.responseText, 
                            this.time, 
                            req.currentRequest,
                            req.req);
                } else if (req.currentRequest.callerror) {
                    req.currentRequest.callerror(
                            req.currentRequest.id, 
                            data, 
                            req.req.responseText, 
                            this.time, 
                            req.currentRequest,
                            req.req);
                }
                req.next();
            }
        }
    };

    this.next = function () {
        this.running = false;
        if (this.enabled && this.pointer < this.nextID) {
            var request = this.queue[this.pointer];
            delete this.queue[this.pointer];
            this.pointer++;
            if (request) {
                if (this.loadXMLDoc(request) === 0) {
                    this.next();
                }
            } else {
                this.next();
            }
        } 
    };
    
    this.add = function (request) {
        var d;
        if (request && request.url && 
                (request.method === "GET" || 
                request.method === "PUT" || 
                request.data)) {
            var id = this.nextID++;
            request.id = id;
            if (request.wait) {
                this.queue[id] = request;
                if (!this.running && this.enabled) {
                    this.next();
                }
            } else {
                this.loadXMLDoc(request);
            }
            return id;
        }
        return -1;
    };
};

if (!axton.data.ajax.queue) {
    axton.data.ajax.queue = new axton.data.ajax.Queue(axton.data.ajax.Cache ? new axton.data.ajax.Cache() : null);
}